package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;


    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)

    public void save(BrandDTO brandDTO) {
        //1.将brandDTO相关的属性封装到brandDTO中
        Brand brand = brandDTO.toEntity(Brand.class);
        //2.保存
        this.save(brand);

        //3.根据传入的分类id获取所有分类
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //4.将分类id和品牌id封装成CategoryBrand对象，并注入到集合中
        List<CategoryBrand> categoryBrandList = categoryIds.stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        //5.保存到中间表中
        categoryBrandService.saveBatch(categoryBrandList);
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public void update(BrandDTO brandDTO) {

        //删除中间表
        QueryWrapper<CategoryBrand> queryWrapper = new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId());
        categoryBrandService.remove(queryWrapper);

        //批量添加中间表
        List<CategoryBrand> categoryBrandList = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brandDTO.getId())).collect(Collectors.toList());
        categoryBrandService.saveBatch(categoryBrandList);

        //修改品牌表
        Brand brand = brandDTO.toEntity(Brand.class);
        this.updateById(brand);

    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long cid) {
        //根据分类id查询中间表
        QueryWrapper<CategoryBrand> queryWrapper = new QueryWrapper<CategoryBrand>().eq("category_id", cid);
        List<CategoryBrand> categoryBrandList = categoryBrandService.list(queryWrapper);

        //获取中间表中的品牌id,根据品牌id查询品牌
        List<Long> brandIdList = categoryBrandList.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());

        List<Brand> brands = null;
        if(brandIdList != null){
            brands = this.listByIds(brandIdList);
        }

        return BrandDTO.convertEntityList(brands);
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPageAndCondition(String key, Long curPage, Long rows) {
        // 1.分页信息的健壮性处理
        curPage = Math.min(curPage,100);
        rows = Math.max(rows,5);
        //2.分页
        IPage<Brand> page = new Page<>(curPage, rows);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<Brand>()
                .eq(!StringUtils.isEmpty(key), "letter", key)
                .or()
                .like(!StringUtils.isEmpty(key), "name", key);

        this.page(page,queryWrapper);
        // 5.封装结果
        List<Brand> brandList = page.getRecords();
        List<BrandDTO> brandDTOList = BrandDTO.convertEntityList(brandList);

        PageDTO<BrandDTO> pageDTO = new PageDTO<>();
        pageDTO.setItems(brandDTOList);
        pageDTO.setTotal(page.getTotal());
        pageDTO.setTotalPage(page.getPages());
        return pageDTO;
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public void deleteBrandById(Long id) {
        this.removeById(id);
        //删除中间表
        QueryWrapper<CategoryBrand> queryWrapper = new QueryWrapper<CategoryBrand>().eq("brand_id", id);
        categoryBrandService.remove(queryWrapper);

    }
}